﻿using BenCaoXuan.Infrastructure.Attr;
using BenCaoXuan.Infrastructure.Dto;
using BenCaoXuan.Infrastructure.Dto.Admin.Arrange;
using BenCaoXuan.Infrastructure.EFCore.MySql;
using BenCaoXuan.Infrastructure.IOC;
using BenCaoXuan.Infrastructure.Tools;
using BenCaoXuan.Service.Interface.admin;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BenCaoXuan.Service.Instance.admin
{
    [Inject_]
    public class Arrange_Service : Base_Service, I_Arrange_Service
    {
        private readonly Arrange_IOC _arrange_IOC;
        private readonly Login_IOC _login_IOC;
        private readonly Sys_IOC _sys_IOC;

        public Arrange_Service(Arrange_IOC arrange_IOC,
            Login_IOC login_IOC,
            Sys_IOC sys_IOC)
        {
            _arrange_IOC = arrange_IOC;
            _login_IOC = login_IOC;
            _sys_IOC = sys_IOC;
        }

        /// <summary>
        /// 获取排班
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Arrange()
        {
            var data = await _arrange_IOC._arrange_EFCore.GetAll()
                .Select(d => new Arrange_Dto
                {
                    id = d.AId,
                    date = d.ADate,
                    doctorsID = d.AEid,
                    timeRange = d.ATimeRange,
                    timeSlot = d.ATimeSlot,
                    doctors = new List<Doctors_Dto>()
                })
                .ToListAsync();
            var allemployee = _login_IOC._sysEmployee_EFCore.GetAll().ToList();
            var alldept = _sys_IOC._sysDepartment_EFCore.GetAll().ToList();
            data.ForEach(d =>
            {
                d.doctorsID.Split(",").ToList().ForEach(c =>
                {
                    var employee = allemployee.Where(k => k.EId == c).SingleOrDefault();
                    d.doctors.Add(new Doctors_Dto()
                    {
                        id = employee.EId,
                        deptID = employee.EDepartmentId,
                        name = employee.EName,
                        avatar=employee.EPhoto

                    });
                });

                d.doctors.ForEach(c =>
                {
                    c.department = alldept.Where(k => k.DId == c.deptID).Select(k => k.DName).SingleOrDefault();
                });
            });

            return Get_Result(0, "ok", data);

        }

        /// <summary>
        /// 获取排班的员工
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Arrange_Employee()
        {
            var data = await _login_IOC._sysEmployee_EFCore.GetAll()
                .Select(d => new ArrangeEmployee_Dto
                {
                    id = d.EId,
                    name = d.EName,
                    deptID = d.EDepartmentId,
                    avatar = d.EPhoto
                }).ToListAsync();

            var alldept = _sys_IOC._sysDepartment_EFCore.GetAll().ToList();
            data.ForEach(d =>
            {
                d.specialty = alldept.Where(c => c.DId == d.deptID).Select(c => c.DName).SingleOrDefault();
            });

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 获取员工的休息日
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_EmployeeRestDay()
        {
            var data = await _arrange_IOC._employeeRestDay_EFCore.GetAll()
                 .Select(d => new RestDay_Dto{ 
                 id=d.ErId,
                 eid=d.ErEid,
                 restDay=d.ErRestDay
                 }).ToListAsync();

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 设置排班
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Set_Arrange(List<SetArrange_Dto> dto)
        {

            dto.ForEach(d =>
            {
                string doctorIdsStr = string.Join(",", d.doctors!);
                Arrange arrange = new Arrange()
                {
                    AId = Config.GUID2(),
                    ATimeRange = d.timeRange,
                    ADesc = d.notes,
                    ACreateTime = DateTime.Now,
                    ADate = d.date,
                    ATimeSlot = d.timeSlot,
                    AEid = doctorIdsStr
                };
                _arrange_IOC._arrange_EFCore.Add(arrange);
            });


            var result = await _arrange_IOC._arrange_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 设置休息日
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Set_EmployeeRestDay(SetRestDay_Dto dto)
        {
            // 先删除该员工已有的休息日记录（避免重复数据）
            var existingRestDays = await _arrange_IOC._employeeRestDay_EFCore
                .GetAll(e => e.ErEid == dto.id)
                .ToListAsync();
            if (existingRestDays.Any())
            {
                _arrange_IOC._employeeRestDay_EFCore.DeleteRange(existingRestDays);
            }

            // 循环创建新的休息日记录（每个休息日对应一个独立对象）
            foreach (var day in dto.restday ?? Enumerable.Empty<int>())
            {
                var employeeRestDay = new EmployeeRestDay
                {
                    ErId = Config.GUID2(), // 生成唯一ID
                    ErEid = dto.id!,       // 员工ID
                    ErRestDay = day,       // 休息日（0-6）
                    ErCreateTime = DateTime.Now
                };
                _arrange_IOC._employeeRestDay_EFCore.Add(employeeRestDay);
            }

            // 保存变更
            var result = await _arrange_IOC._employeeRestDay_EFCore.SaveChangesAsync();
            return Get_Result(result); // 只要有一条数据成功保存就返回成功
        }

        /// <summary>
        /// 编辑排班
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Update_Arrange(UpdateArrange_Dto dto)
        {
            var data =await _arrange_IOC._arrange_EFCore.GetAll(d => d.AId == dto.id).SingleAsync();
            data.AEid = dto.eid;
            _arrange_IOC._arrange_EFCore.Update(data);
            var result = await _arrange_IOC._arrange_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }
    }
    }
